﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Arcadia.Bookasa.Common;
using Arcadia.Bookasa.Common.Service;
using System.Threading;

namespace Arcadia.Bookasa.Host
{
    public class BookasaServiceHost : IServiceHost
    {
        public List<IServiceExtension> ServiceList { get; set; }


        public void Startup()
        {
            foreach (var service in this.ServiceList)
            {
                service.Activate(this);
            }
        }

        public void Shutdown()
        {
            foreach (var service in this.ServiceList)
            {
                service.Deactivate ();
            }
        }


        public List<T> GetFunctionExtensions<T>(ExtensionCategory category)
        {
            List<IServiceExtension> objs = this.ServiceList.FindAll(m => m.IsSupport<T>());

            List<T> lists = new List<T>();
            foreach (var obj in objs)
            {
                lists.Add(obj.GetInterface<T>());
            }
            return lists;
        }

        public T GetFunctionExtension<T>()
        {
            IServiceExtension service = this.ServiceList.Find(m => m.IsSupport<T>());

            return service.GetInterface<T>();
        }
        
        public void RunInBackground(IBackgroundWorking worker)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback (worker.Running));
        }
    }
}
